﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
    public static partial class user
    {
        public static dynamic deleteUser(string username)
        {
            var sql = new Sql.SqlDataContext();
            var u = sql.User.FirstOrDefault(row => row.username.ToLower() == username.ToLower());
            if (u == null) return new
                {
                    success = false,
                    msg = "用户不存在"
                };

            // Delete Status
            var sts = sql.Status.Where(row => row.username == u.username);
            foreach (var st in sts)
            {
                if (st.status < 3 || st.god) continue;
                // Update PS
                var ps = sql.ProblemStatistics.FirstOrDefault(row => row.pid == st.pid);
                if (ps != null) problem.deleteProblemStatistics(ps, st.status);
            }
            sql.Status.DeleteAllOnSubmit(sts);

            // Delete US
            var us = sql.UserStatistics.FirstOrDefault(row => row.username == u.username);
            if (us != null) sql.UserStatistics.DeleteOnSubmit(us);

            // Delete Solve
            sql.Solve.DeleteAllOnSubmit(sql.Solve.Where(row => row.username == u.username));

            // Delete Discuss
            sql.Discuss.DeleteAllOnSubmit(sql.Discuss.Where(row => row.username == u.username));

            // Delete Msg
            sql.Message.DeleteAllOnSubmit(sql.Message.Where(row => row.from == u.username || row.to == u.username));

            // Delete User
            sql.User.DeleteOnSubmit(u);
            sql.SubmitChanges();
            return new
            {
                success = true
            };
        }

        internal static void deleteUserStatistics(Sql.UserStatistics us, int status)
        {
            if (status >= 3) --us.submit;
            switch (status)
            {
                case 3:
                    --us.accept;
                    break;
                case 4:
                    --us.pe;
                    break;
                case 5:
                    --us.tle;
                    break;
                case 6:
                    --us.mle;
                    break;
                case 7:
                    --us.ole;
                    break;
                case 8:
                    --us.wa;
                    break;
                case 9:
                    --us.re;
                    break;
                case 10:
                    --us.ce;
                    break;
                case 11:
                    --us.se;
                    break;
            }
        }
    }
}
